import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {UserTableComponent} from "../../shared/component/user-table/user-table.component";
import {FileUploadComponent} from "../../shared/component/file-upload/file-upload.component";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {Http} from "@angular/http";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {DriverService} from "../../shared/service/driver.service";
import {Driver} from "../../shared/model/driver";
declare var $:any;

@Component({
  selector: 'app-driver-edit-form',
  templateUrl: './driver-edit-form.component.html',
  styleUrls: ['./driver-edit-form.component.css']
})
export class DriverEditFormComponent implements OnInit {

  radioValue:number;
  driverForm:FormGroup;
  driver:Driver;
  @ViewChild(UserTableComponent) userTable :UserTableComponent;
  @ViewChild(FileUploadComponent) child :FileUploadComponent;
  userId:string = this.routeInfo.snapshot.queryParams ["userId"];
  _date = null;
  licenseTypes:any=[{
    "id":"A1",
    "name":"A1"
  },{
    "id":"A2",
    "name":"A2"
  },{
    "id":"A3",
    "name":"A3"
  },{
    "id":"B1",
    "name":"B1"
  },{
    "id":"B2",
    "name":"B2"
  },{
    "id":"C1",
    "name":"C1"
  },{
    "id":"C2",
    "name":"C2"
  },{
    "id":"C3",
    "name":"C3"
  },{
    "id":"C4",
    "name":"C4"
  },{
    "id":"D",
    "name":"D"
  },{
    "id":"E",
    "name":"E"
  },{
    "id":"F",
    "name":"F"
  },{
    "id":"M",
    "name":"M"
  },{
    "id":"N",
    "name":"N"
  },{
    "id":"P",
    "name":"P"
  }];

  constructor(
    private routeInfo:ActivatedRoute,
    private fb:FormBuilder,
    private singleOpenWinService:SingleOpenWinService,
    private driverService:DriverService,
    private router:Router
  ) { }

  ngOnInit() {
    this.createForm();

    //初始化出生年月
    $('#birthdays').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //初始化领证日期
    $('#certificationDates').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //订阅司机开窗
    // this.singleOpenWinService.valueChange.subscribe((info:string)=>{
    //   console.log("edit");
    //   $('#id').val(this.userTable.selected.id);
    //   $('#name').val(this.userTable.selected.name);
    //   this.driverForm.patchValue({
    //     id:this.userTable.selected.id,
    //     name:this.userTable.selected.name
    //   });
    //   this.userIsVisible = false;
    // });

    this.routeInfo.paramMap
      .switchMap((params: ParamMap) => this.driverService.getDriverByOid(this.routeInfo.snapshot.params["oid"]))
      .subscribe(driver => {
        this.driver = driver.driver;
        this.driverForm.reset({
          oid:this.driver.oid,
          id:this.driver.id,
          name:this.driver.name,
          birthday:this.driver.birthday,
          gender:this.driver.gender,
          phone:this.driver.phone,
          licenseType:this.driver.licenseType,
          certificationDate:this.driver.certificationDate
        });
        this.radioValue = this.driver.gender;
        let date = $('#birthday').val();
        $('#birthday').val(date.split(" ")[0]);
        date = $('#certificationDate').val();
        $('#certificationDate').val(date.split(" ")[0]);
        $('#licenseType').val(this.driver.licenseType);
      });
  }

  createForm(){
    this.driverForm =this.fb.group({
      oid:'',
      id: '',
      name: '',
      birthday: '',
      gender: '',
      phone: '',
      licenseType: '',
      certificationDate: '',
      creator:this.userId
    });
    // this.radioValue =1;
  }

  /**
   *  单选人员开窗
   */
  userIsVisible = false;

  userShowModal = () => {
    this.userIsVisible = true;
  }

  userHandleCancel = (e) => {
    this.userIsVisible = false;
  }

  //司机信息开窗
  driverOpenWin(){
    this.userShowModal();
  }

  onSubmit(val:any){
    if(this.checkFormData()){
      this.driverForm.patchValue({
        birthday:$('#birthday').val(),
        certificationDate:$('#certificationDate').val()
      });
      this.driverService.updateDriver(this.driverForm.value,this.child.fileoids).then(res=>{
        if(res.code ===1){
          alert(res.message);
          this.driverService.listFreshEvent.emit("edit");
          this.driverService.searchFreshEvent.emit("edit");
          this.driverForm.reset();
          //清空附件列表信息
          this.child.fileList = [];
          this.router.navigateByUrl('driver/new');
        }else{
          alert(res.message);
        }
      });
    }
  }

  checkFormData(){
    let msg ="";
    let regexp=/^0\d{2,3}-[1-9]\d{6,7}$|^[1][3,4,5,7,8][0-9]{9}$/;  //判断为电话号码
    if(!this.driverForm.get("id").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入司机代号\n");
    }
    if(!this.driverForm.get("name").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入司机名称\n");
    }
    if (typeof(this.driverForm.get("gender").value) == "undefined") {
      msg += ("请选择司机性别\n");
    }
    if (!this.driverForm.get("phone").value.replace(/^\s+|\s+$/g,"")) {
      msg += ("请输入电话号码\n");
    }
    if(this.driverForm.get("phone").value && !regexp.test(this.driverForm.get("phone").value)){
      msg +=("请输入有效的电话号码\n");
    }
    if(!this.driverForm.get("licenseType").value){
      msg +=("请选择准驾车型\n");
    }
    if(msg){
      alert(msg);
      return false;
    }else{
      return true;
    }
  }

}
